//
//  DXYReadViewController.m
//  Piece
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "DXYReadViewController.h"
#import "DYJScrollView.h"
#import "ZHNetworkHandler.h"
#import "DYJScrollViewModel.h"
#import "DYJTapScrollViewViewController.h"
#import "DYJReadCollectionViewCell.h"
#import "DYJShortModel.h"
#import "DYJSerialModel.h"
#import "DYJQuestionModel.h"
#import "DYJReadTableView.h"
#import "DYJShortViewController.h"
#import "DYJSerialViewController.h"
#import "DYJQuestionViewController.h"
#import "XZHSearchViewController.h"
#import "AAPullToRefresh.h"
#import "DYJDateListViewController.h"
#import "FeHourGlass.h"
#import "ZHArchiverTools.h"
@interface DXYReadViewController ()<DYJScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, DYJReadTableViewDelegate>
//滚动视图
@property (nonatomic, strong) DYJScrollView *headerScrollView;
//滚动视图数据源数组
@property (nonatomic, strong) NSMutableArray *headerScrollViewDataArray;
//阅读内容collectionView
@property (nonatomic, strong) UICollectionView *readCollectionView;
//短片数据源数组
@property (nonatomic, strong) NSMutableArray *shortDataArray;
//连载数据源数组
@property (nonatomic, strong) NSMutableArray *serialDataArray;
//问题数据源数组
@property (nonatomic, strong) NSMutableArray *questionDataArray;

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (strong, nonatomic) FeHourGlass *hourGlass;

@end

@implementation DXYReadViewController
- (void)dealloc
{
    _headerScrollView.delegate = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self createNavigationBarButtonWithPicture:@"plant" Picture:@""];

    [self createTitle:@"阅读"];
    [self createNavigationBarButtonWithPicture:@"plant" Picture:@"play"];

    self.view.backgroundColor = [UIColor colorWithRed:0.51 green:0.81 blue:0.64 alpha:1.00];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.76 green:0.79 blue:0.83 alpha:1.00];
    //初始化数据源数组
    self.shortDataArray = [NSMutableArray array];
    self.serialDataArray = [NSMutableArray array];
    self.questionDataArray = [NSMutableArray array];
    //初始化滚动视图数据源数组
    _headerScrollViewDataArray = [NSMutableArray array];
    
    [self createReadCollectionView];
    
    //创建滚动视图
    _headerScrollView = [[DYJScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 170 * FitHeight)];
    _headerScrollView.delegate = self;
    [self.view addSubview:_headerScrollView];
    [self getAllData];
    [self getNewData];
    
    [self getDateListViewController];

}
#pragma mark -- 获取滚动视图数据
- (void)getScrollViewDataByDictionary:(NSDictionary *)dictionary
{
    //清除滚动视图数据源数组
    [_headerScrollViewDataArray removeAllObjects];
    NSArray *dataArray = [dictionary valueForKey:@"data"];
    for (NSDictionary *dic in dataArray) {
        DYJScrollViewModel *scrollViewModel = [[DYJScrollViewModel alloc] initWithDic:dic];
        [_headerScrollViewDataArray addObject:scrollViewModel];
    }
    [_headerScrollViewDataArray insertObject:[_headerScrollViewDataArray lastObject] atIndex:0];
    [_headerScrollViewDataArray addObject:[_headerScrollViewDataArray objectAtIndex:1]];
    self.headerScrollView.scrollArray = _headerScrollViewDataArray;
 }
#pragma mark -- 滚动视图代理方法
- (void)pushTapScrollViewControllerById:(NSString *)id ColorBy:(NSInteger)item Tilte:(NSString *)title
{
    //点击滚动视图跳转界面
    DYJTapScrollViewViewController *tsvvc = [[DYJTapScrollViewViewController alloc] init];
    tsvvc.id = id;
    tsvvc.colorNum = item;
    tsvvc.readTitle = title;
    [self.navigationController pushViewController:tsvvc animated:YES];
}
#pragma mark -- 创建阅读内容collectionView
- (void)createReadCollectionView
{
    //布局
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 64 - 49 - 170 * FitHeight);
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //初始化collectionView
    self.readCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 170 * FitHeight, ScreenWidth, ScreenHeight - 64 - 49 - 170 * FitHeight) collectionViewLayout:_flowLayout];
    self.readCollectionView.backgroundColor = [UIColor whiteColor];
    self.readCollectionView.pagingEnabled = YES;
    self.readCollectionView.delegate = self;
    self.readCollectionView.dataSource = self;
    [self.view addSubview:_readCollectionView];
    //注册cell
    [self.readCollectionView registerClass:[DYJReadCollectionViewCell class] forCellWithReuseIdentifier:@"readCell"];
}

#pragma mark -- 阅读内容解析
- (void)getReadDataByDictionary:(NSDictionary *)dictionary
{
    //清除数据源数组
    [self.shortDataArray removeAllObjects];
    [self.serialDataArray removeAllObjects];
    [self.questionDataArray removeAllObjects];
    //逐层解析
    NSDictionary *dataDic = [dictionary valueForKey:@"data"];
    NSArray *essayArray = [dataDic valueForKey:@"essay"];
    
    for (NSDictionary *dic in essayArray) {
        DYJShortModel *shortModel = [[DYJShortModel alloc] initWithDic:dic];
        [self.shortDataArray addObject:shortModel];
    }
    NSArray *serialArray = [dataDic valueForKey:@"serial"];
    for (NSDictionary *dic in serialArray) {
        DYJSerialModel *serialModel = [[DYJSerialModel alloc] initWithDic:dic];
        [self.serialDataArray addObject:serialModel];
    }
    NSArray *questionArray = [dataDic valueForKey:@"question"];
    for (NSDictionary *dic in questionArray) {
        DYJQuestionModel *questionModel = [[DYJQuestionModel alloc] initWithDic:dic];
        [self.questionDataArray addObject:questionModel];
    }
    [self.readCollectionView reloadData];
}
- (void)myTask
{
    // Do something usefull in here instead of sleeping ...
    sleep(6);
}

#pragma mark -- 整体数据解析
- (void)getAllData
{
    _hourGlass = [[FeHourGlass alloc] initWithView:self.readCollectionView];
    [self.view addSubview:_hourGlass];
    _hourGlass.frame = CGRectMake(0, 80, ScreenWidth, ScreenHeight - 64 - 49 - 80);
    [_hourGlass showWhileExecutingBlock:^{
        [self myTask];
    } completion:^{
        
        
    }];

    [ZHNetworkHandler getDataByURLString:@"http://v3.wufazhuce.com:8000/api/reading/carousel" WithBodyString:nil WithHeaderDic:nil WithResponse:0 WithSuccess:^(id result) {
        NSDictionary *dictionary = (NSDictionary *)result;
        [ZHArchiverTools archiverObject:dictionary ByKey:@"scrollCache" WithPath:@"scroll.plist"];
        [self getScrollViewDataByDictionary:dictionary];
    } WithFailure:^(NSError *error) {
        NSDictionary *dictionary = [ZHArchiverTools unarchiverObjectByKey:@"scrollCache" WithPath:@"scroll.plist"];
        if (dictionary == nil) {
            
        }
        else
        {
            [self getScrollViewDataByDictionary:dictionary];

        }
    }];
    [ZHNetworkHandler getDataByURLString:@"http://v3.wufazhuce.com:8000/api/reading/index" WithBodyString:nil WithHeaderDic:nil WithResponse:0 WithSuccess:^(id result) {
        NSDictionary *dictionary = (NSDictionary *)result;
        [ZHArchiverTools archiverObject:dictionary ByKey:@"readCache" WithPath:@"read.plist"];
        [self getReadDataByDictionary:dictionary];
        [_hourGlass removeFromSuperview];

      
    } WithFailure:^(NSError *error) {
        NSDictionary *dictionary = [ZHArchiverTools unarchiverObjectByKey:@"readCache" WithPath:@"read.plist"];
        if (dictionary == nil) {
            
        }
        else
        {
            [self getReadDataByDictionary:dictionary];
            [_hourGlass removeFromSuperview];
        }

    }];

}
#pragma mark -- 右拉刷新
- (void)getNewData
{
    /********************   刷新  *****************************/
    __weak DXYReadViewController *weakSelf = self;
    AAPullToRefresh *pullToRefreshLeft = [self.readCollectionView addPullToRefreshPosition:AAPullToRefreshPositionLeft actionHandler:^(AAPullToRefresh *left) {
        [left performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
        [weakSelf getAllData];
        [weakSelf.readCollectionView setContentOffset:CGPointMake(0, 0) animated:NO];
        weakSelf.flowLayout.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 40 - 64 - 49 - 170 * FitHeight);
        weakSelf.flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }];
    //拉动开始刷新值:
    pullToRefreshLeft.threshold = 60;
    //小圈的颜色:
    pullToRefreshLeft.borderColor = [UIColor colorWithRed:0.54 green:0.69 blue:0.84 alpha:1.00];
    //小圈的边界宽:
    pullToRefreshLeft.borderWidth = 4;
    pullToRefreshLeft.imageIcon = [UIImage new];
    /*************************************************/

}
#pragma mark -- 左拉推日期列表界面
- (void)getDateListViewController
{
    __weak DXYReadViewController *weakSelf = self;
    //左拉加载更多:
    AAPullToRefresh *pullToRefreshRight = [self.readCollectionView addPullToRefreshPosition:AAPullToRefreshPositionRight actionHandler:^(AAPullToRefresh *right) {
        
        DYJDateListViewController *dlvc = [[DYJDateListViewController alloc] init];
        [weakSelf.navigationController pushViewController:dlvc animated:YES];
        [right performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
        weakSelf.flowLayout.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 40 - 64 - 49 - 170 * FitHeight);
    }];
   // pullToRefreshRight.borderColor = LYLAppThemeColor;
    pullToRefreshRight.borderColor = [UIColor colorWithRed:0.54 green:0.69 blue:0.84 alpha:1.00];
    pullToRefreshRight.threshold = 60;
    pullToRefreshRight.borderWidth = 4;
    pullToRefreshRight.imageIcon = [UIImage new];
}

#pragma mark -- collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _shortDataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DYJReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"readCell" forIndexPath:indexPath];
    DYJShortModel *shortModel = [_shortDataArray objectAtIndex:indexPath.item];
    DYJSerialModel *serialModel = [_serialDataArray objectAtIndex:indexPath.item];
    DYJQuestionModel *questionModel = [_questionDataArray objectAtIndex:indexPath.item];
    cell.shortModel = shortModel;
    cell.serialModel = serialModel;
    cell.questionModel = questionModel;
    cell.readTableView.delegate = self;
    
    return cell;
}

#pragma mark -- 实现readTableView代理方法
- (void)pushShortViewControllerById:(NSString *)contentId
{
    DYJShortViewController *svc = [[DYJShortViewController alloc] init];
    svc.shortId = contentId;
    [self.navigationController pushViewController:svc animated:YES];
}
- (void)pushSerialViewControllerById:(NSString *)serialId
{
    DYJSerialViewController *sevc = [[DYJSerialViewController alloc] init];
    sevc.serialId = serialId;
    [self.navigationController pushViewController:sevc animated:YES];
}
- (void)pushQuestionViewControllerById:(NSString *)questionId
{
    DYJQuestionViewController *qvc = [[DYJQuestionViewController alloc] init];
    qvc.questionId = questionId;
    [self.navigationController pushViewController:qvc animated:YES];
}
- (void)pushSearchViewController
{
    XZHSearchViewController *svc = [[XZHSearchViewController alloc] init];
    [self.navigationController pushViewController:svc animated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    //[self.view bringSubviewToFront:self.playView];
    [_hourGlass showWhileExecutingBlock:^{
        //[self myTask];
    } completion:^{
        
        
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
